library(pheatmap)
Args <- commandArgs()

# /usr/bin/Rscript kmean_cluster_heatmap.R test.txt test.png 5
# Args[6]= test.txt  Args[7]= test.png 

input_file = Args[6]
out_file   = Args[7]
kmean = Args[8]

outfile_kmean = paste(out_file,".kmean",sep = "")
title = paste("Clustered Heatmap(K-means=",kmean,")")
#cat(input_file)
matrix=read.csv(input_file,header=T,row.names=1)
km = kmeans(matrix,kmean)
write(km$cluster,outfile_kmean)
#print(km$cluster)
#o <- order(km$cluster)
#m3 <- matrix[o, ]
#print(matrix)

#matrix2 = cbind(matrix,km$cluster)
kmcluster = km$cluster
m_col_num = ncol(matrix)
m_row_num = nrow(matrix)

#par(mfrow=c(1,1))
#par(mgp=c(1.6,10,10),mar=c(10,3,2,1))
for(rep_num in 1:kmean){
    flag=0
	max_area=0
	for(x in 1:m_row_num){
  		if(kmcluster[x]==rep_num){
    		max_area_tmp = max(matrix[x,])
    		max_area = ifelse(max_area_tmp>max_area,max_area_tmp,max_area)
  		}
  		#print(max_area)
	}
	kmean_plot_out = paste(out_file,".kmeanCluster_",rep_num,".png",sep = "")
	png(kmean_plot_out,width=1000,height=1000)
	for(x in 1:m_row_num){
  		if(kmcluster[x]==rep_num){
    		flag = flag+1
    		if(flag==1){
        		plot(panel.first=grid(),type="l",c(1:m_col_num),c(matrix[x,]),xaxt="n",ylab="Area",xlab="",main=paste("K-mean cluster",rep_num),ylim=c(0,max_area))
        		axis(1,labels= colnames(matrix),at=1:m_col_num,las=1)
    		}
    		else{
      			lines(c(1:m_col_num),c(matrix[x,]))
    		}
        	points(c(1:m_col_num),c(matrix[x,]), pch=1,cex =1, col = "dark red")
  		}
	}
	dev.off()
}


#colnames(matrix)=c('c1','c2','c3','c4')
#rownames(matrix)=c('r1','r2','r3','r4')
#png(out_file)
png(out_file, type="cairo",units="in",width = 5, height = 5,pointsize=5.2,res=300)
pheatmap(km$centers,cluster_rows=0,cluster_cols=0, fontsize=9, fontsize_row=16,border_color = "white",main =title )

dev.off()